<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片生成器</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background-color: #f0f2f5; margin: 0; padding: 0; display: flex; height: 100vh; }
        .sidebar { width: 400px; background-color: #ffffff; padding: 20px; box-shadow: 2px 0 5px rgba(0,0,0,0.1); overflow-y: auto; }
        .main-content { flex-grow: 1; padding: 40px; display: flex; justify-content: center; align-items: center; background-color: #e9ebee; }
        .image-container { max-width: 100%; max-height: 100%; box-shadow: 0 4px 8px rgba(0,0,0,0.1); background-color: white; padding: 10px; border-radius: 8px; }
        #generated-image { max-width: 100%; max-height: calc(100vh - 100px); display: block; }
        h2 { color: #333; border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-top: 0; }
        fieldset { border: 1px solid #ddd; border-radius: 4px; padding: 10px; margin-bottom: 10px; }
        legend { font-weight: 500; color: #333; padding: 0 5px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: 500; color: #555; }
        input[type="text"], input[type="number"], select, textarea { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        input[type="color"] { width: 100%; height: 40px; padding: 5px; border-radius: 4px; box-sizing: border-box; border: 1px solid #ccc; }
        input[type="checkbox"] { margin-right: 5px; }
        .btn { display: block; width: 100%; padding: 12px; background-color: #007bff; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; text-align: center; text-decoration: none; margin-top: 10px; }
        .btn:hover { background-color: #0056b3; }
        .btn-download { background-color: #28a745; }
        .btn-download:hover { background-color: #218838; }
        .hidden { display: none; }
    </style>
</head>
<body>

<div class="sidebar">
    <h2>图片生成设置</h2>
    <form id="config-form">
        <div class="form-group">
            <label for="config-select">选择模板:</label>
            <select id="config-select" name="selected_config">
                {% for file in config_files %}
                    <option value="{{ file }}" {% if file == selected_config %}selected{% endif %}>{{ file.replace('.yml', '') }}</option>
                {% endfor %}
            </select>
        </div>

        <div id="form-parameters">
            <!-- Parameters will be loaded here by JavaScript -->
        </div>

        <button type="submit" class="btn">生成图片</button>
        <a id="download-btn" href="{{ initial_image_url or '#' }}" class="btn btn-download {% if not initial_image_url %}hidden{% endif %}" download="generated_image.png">下载图片</a>
    </form>
</div>

<div class="main-content">
    <div class="image-container">
        <img id="generated-image" src="{{ initial_image_url or '' }}" alt="生成的图片会显示在这里">
    </div>
</div>

<script>
    const formParametersDiv = document.getElementById('form-parameters');
    const configSelect = document.getElementById('config-select');
    const configForm = document.getElementById('config-form');
    const generatedImage = document.getElementById('generated-image');
    const downloadBtn = document.getElementById('download-btn');

    const keyToChinese = {
        'width': '宽度', 'height': '高度', 'background_color': '背景色',
        'grid': '网格', 'enabled': '启用', 'line_color': '线条颜色', 'step': '步长',
        'svg': 'SVG 图标', 'content': '内容', 'size': '大小', 'y_position': 'Y坐标',
        'title': '标题', 'font_size': '字号', 'font_color': '颜色', 'bold_font_color': '粗体颜色',
        'shadow_color': '阴影颜色', 'shadow_offset': '阴影偏移',
        'footnote': '脚注', 'text': '文字', 'padding': '内边距',
        'fonts': '字体', 'regular': '常规字体', 'bold': '粗体字体', 'output_dir': '输出目录'
    };

    function buildForm(config, container) {
        container.innerHTML = '';
        
        const mainTitleText = config.title.texts_to_generate ? config.title.texts_to_generate.join('\\n') : '';
        const titleGroup = createFormGroup('main_title_text', '标题文字 (一行一个)', 'textarea', mainTitleText);
        container.appendChild(titleGroup);

        function createFields(obj, parentKey = '', parentElement) {
            for (const key in obj) {
                if (key === 'texts_to_generate') continue;

                const value = obj[key];
                const newKey = parentKey ? `${parentKey}.${key}` : key;

                if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
                    const fieldset = document.createElement('fieldset');
                    fieldset.innerHTML = `<legend>${keyToChinese[key] || key}</legend>`;
                    parentElement.appendChild(fieldset);
                    createFields(value, newKey, fieldset);
                } else {
                    let type = 'text';
                    if (typeof value === 'boolean') type = 'checkbox';
                    else if (key === 'content' && parentKey === 'svg') type = 'textarea';
                    else if (typeof value === 'number') type = 'number';
                    else if (String(value).startsWith('#')) type = 'color';
                    
                    const group = createFormGroup(newKey, keyToChinese[key] || key, type, value);
                    parentElement.appendChild(group);
                }
            }
        }
        createFields(config, '', container);
    }

    function createFormGroup(id, labelText, type, value) {
        const group = document.createElement('div');
        group.className = 'form-group';
        const label = document.createElement('label');
        label.setAttribute('for', id);
        label.textContent = labelText;
        
        let input;
        if (type === 'textarea') {
            input = document.createElement('textarea');
            input.value = value;
            input.rows = (id === 'svg.content') ? 8 : 3;
        } else {
            input = document.createElement('input');
            input.type = type;
            if (type === 'checkbox') {
                input.checked = value;
                input.value = 'true';
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = id;
                hiddenInput.value = 'false';
                group.appendChild(hiddenInput);
            } else {
                 input.value = value;
            }
        }
        input.id = id;
        input.name = id;
        
        group.appendChild(label);
        group.appendChild(input);
        return group;
    }

    async function loadConfig(filename) {
        try {
            const response = await fetch(`/load_config/${filename}`);
            if (!response.ok) throw new Error('配置加载失败');
            const config = await response.json();
            buildForm(config, formParametersDiv);
        } catch (error) {
            console.error('加载配置时出错:', error);
            formParametersDiv.innerHTML = '<p style="color:red;">无法加载配置。</p>';
        }
    }

    configSelect.addEventListener('change', (e) => {
        loadConfig(e.target.value);
    });

    configForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(configForm);
        const submitButton = configForm.querySelector('button[type="submit"]');
        submitButton.textContent = '生成中...';
        submitButton.disabled = true;

        try {
            const response = await fetch('/generate', {
                method: 'POST',
                body: formData
            });
            if (!response.ok) throw new Error('图片生成失败');
            const result = await response.json();

            generatedImage.src = result.image_url + '?t=' + new Date().getTime();
            downloadBtn.href = result.image_url;
            downloadBtn.classList.remove('hidden');

        } catch (error) {
            console.error('生成图片时出错:', error);
            alert('生成图片失败，请查看浏览器控制台获取详细信息。');
        } finally {
            submitButton.textContent = '生成图片';
            submitButton.disabled = false;
        }
    });

    loadConfig(configSelect.value);

</script>
</body>
</html>
